package domein;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Server extends ServerSocket implements Runnable{
    private int port = 1235, backlog = 50;
    private boolean alive = false;
    private ArrayList<Service> services = new ArrayList<Service>();
    private Thread thread;
    private Control contr;
    
    public Server(int port, int backlog) throws IOException{
        super(port, backlog);
    }
    
    public Server(int port, int backlog, InetAddress host) throws IOException{
   	 super(port, backlog,host);
    }
    
    public Server(int port, int backlog, InetAddress host, Control contr) throws IOException{
   	 this(port,backlog,host);
   	 this.contr = contr;
    }
    
    public boolean isAlive(){
        return this.alive;
    }

    public void stop(){
        for(Service x : services){
            x.stopRun();
        }
        this.alive = false;
        this.thread = null;
    }

    public void run() {
        try {
            this.alive = true;
            while(alive){
                Service klantje = new Service( accept() );
                contr.addPane(klantje.getTextPane());
                klantje.setContentBase(contr.getContentBase());
                services.add( klantje );
                klantje.start();
                System.out.println("Nieuwe verbinding..");
            }
        } catch (IOException ex) {
            System.out.println("Foutje: " + ex);
            for(Service x : services){
                x.stopRun();
            }
        }
    }

    public void start() {
        if(thread == null){
            thread = new Thread(this); 
        }
        thread.start();
    }
}
